package com.yz.jdd.module.help;



import android.content.ComponentName;
import android.content.Context;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import androidx.core.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseActivity;


public class HelpActivity extends BaseActivity implements View.OnClickListener {
    ImageView back;
    TextView title;
    TextView state;
    ImageView voice_lay_img;
    TextView voice_open;

    ImageView autorun_lay_img;
    TextView autorun_open;

    ImageView background_lay_img;
    TextView background_open;

    ImageView ignobattery_lay_img;
    TextView ignobattery_open;

    RelativeLayout background_lay ;
    RelativeLayout autorun_lay;

    private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
    private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_help);
        initView();

    }

    private void initView() {
        back = (ImageView) findViewById(R.id.top_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        title = (TextView) findViewById(R.id.top_title);
        title.setText("语音播报优化");

        state = (TextView) findViewById(R.id.state);


        voice_lay_img = (ImageView) findViewById(R.id.voice_lay_img);
        voice_open = (TextView) findViewById(R.id.voice_open);
        voice_open.setOnClickListener(this);

        autorun_lay_img = (ImageView) findViewById(R.id.autorun_lay_img);
        autorun_open = (TextView) findViewById(R.id.autorun_open);
        autorun_open.setOnClickListener(this);

        background_lay_img = (ImageView) findViewById(R.id.background_lay_img);
        background_open = (TextView) findViewById(R.id.background_open);
        background_open.setOnClickListener(this);

        ignobattery_lay_img = (ImageView) findViewById(R.id.ignobattery_lay_img);
        ignobattery_open = (TextView) findViewById(R.id.ignobattery_open);
        ignobattery_open.setOnClickListener(this);

       background_lay= (RelativeLayout) findViewById(R.id.background_lay);
         autorun_lay= (RelativeLayout) findViewById(R.id.autorun_lay);
    }

    @Override
    protected void onResume() {
        super.onResume();
        showView();

    }

    @Override
    public void onClick(View view) {
        if (view.equals(back)) {
            finish();
        } else if (view.equals(voice_open)) {
            goToOpenNotify();
        } else if (view.equals(background_open)) {
            goToBackgroundRun();
//            MyIntentWrapper.whiteListMatters(this, "");
        } else if (view.equals(autorun_open)) {
            goToAutoRun();
        } else if (view.equals(ignobattery_open)) {
            ignoreBattery(this);
        }
    }


    public void showView() {
        if (isNotificationEnabled(this)) {
            //有通知栏权限
            voice_open.setText("已开启");
            voice_open.setEnabled(false);
            voice_lay_img.setImageResource(R.mipmap.voice_img_blue);

        } else {
            voice_open.setText("去设置");
            voice_open.setEnabled(true);
            voice_lay_img.setImageResource(R.mipmap.voice_img_gray);
        }

        if (!isIgnoreBattery(this)) {
            //忽略电池

            ignobattery_open.setText("去设置");
            ignobattery_open.setEnabled(true);
            ignobattery_lay_img.setImageResource(R.mipmap.battery_img_gray);

        } else {
            ignobattery_open.setText("已开启");
            ignobattery_open.setEnabled(false);
            ignobattery_lay_img.setImageResource(R.mipmap.battery_img_blue);

        }

//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
//            background_lay.setVisibility(View.GONE);
//            autorun_lay.setVisibility(View.GONE);
//        }

    }

    /**
     * 是否开启通知权限
     *
     * @param context
     * @return
     */
    public boolean isNotificationEnabled(Context context) {
//        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
//        ApplicationInfo appInfo = context.getApplicationInfo();
//        String pkg = context.getApplicationContext().getPackageName();
//        int uid = appInfo.uid;
//        Class appOpsClass = null; /* Context.APP_OPS_MANAGER */
//        try {
//            appOpsClass = Class.forName(AppOpsManager.class.getName());
//            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
//            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
//            int value = (Integer) opPostNotificationValue.get(Integer.class);
//            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
        boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
//        Log.e("lkf", "areNotificationsEnabled==" + areNotificationsEnabled);
        return areNotificationsEnabled;

    }

    /**
     * 打开通知栏
     */
    public void goToOpenNotify() {
        if (!isNotificationEnabled(this)) {

            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
            }
            startActivity(localIntent);
        }


    }

    /**
     * 后台运行
     */
    public void goToBackgroundRun() {
//

        String deviceBrand = Build.BRAND;
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ComponentName comp = null;
        if (!TextUtils.isEmpty(deviceBrand)) {
            if ("honor".equals(deviceBrand.toLowerCase()) || "huawei".equals(deviceBrand.toLowerCase())) {
             comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
            } else if ("xiaomi".equals(deviceBrand.toLowerCase())) {
                comp = new ComponentName("com.miui.powerkeeper", "com.miui.powerkeeper.ui.HiddenAppsConfigActivity");
                intent.putExtra("package_name",HelpActivity.this.getPackageName());
                String sApplicationName;
                try {
                    PackageManager pm = HelpActivity.this.getPackageManager();
                    ApplicationInfo ai = pm.getApplicationInfo(HelpActivity.this.getPackageName(), 0);
                    sApplicationName = pm.getApplicationLabel(ai).toString();
                } catch (PackageManager.NameNotFoundException var3) {
                    var3.printStackTrace();
                    sApplicationName = HelpActivity.this.getPackageName();
                }
                intent.putExtra("package_label", sApplicationName);

            } else if ("vivo".equals(deviceBrand.toLowerCase())) {
                //Vivo 后台高耗电
                comp = new ComponentName("com.vivo.abe", "com.vivo.applicationbehaviorengine.ui.ExcessivePowerManagerActivity");

            } else if ("oppo".equals(deviceBrand.toLowerCase())) {

            } else if ("samsung".equals(deviceBrand.toLowerCase())) {
                comp=new ComponentName("com.samsung.android.sm_cn", "com.samsung.android.sm.ui.battery.BatteryActivity");
            }else if("meizu".equals(deviceBrand.toLowerCase())){

//                comp=new ComponentName("com.meizu.safe", "com.meizu.safe.powerui.PowerAppPermissionActivity");
//                comp=new ComponentName("com.meizu.safe","com.meizu.safe.newpermission.ui.AppPermissionsActivity");

                //魅族 应用详情7.0
                intent.setAction("com.meizu.safe.security.SHOW_APPSEC");
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.putExtra("packageName", HelpActivity.this.getPackageName());


            }else if("letv".equals(deviceBrand.toLowerCase())){
                comp= new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.BackgroundAppManageActivity");
            }else if("lenovo".equals(deviceBrand.toLowerCase())){
                comp=new ComponentName("com.lenovo.powersetting", "com.lenovo.powersetting.ui.Settings$HighPowerApplicationsActivity");
            }else if("zte".equals(deviceBrand.toLowerCase())){
                comp=new ComponentName("com.zte.heartyservice", "com.zte.heartyservice.setting.ClearAppSettingsActivity");
            }
            //其他机型直接跳设置界面，适配的几个厂商中有不同系列的手机，可能会跳不到指定界面，因此需要在异常时调到普通设置界面做保护
            try {

                    intent.setComponent(comp);
                    startActivity(intent);

            } catch (Exception e) {//抛出异常就直接打开设置页面
                showToast("您的手机暂不需设置此功能，可跳过");

            }

        }
    }


    /**
     * 打开自启动
     */
    public void goToAutoRun() {
        String deviceBrand = Build.BRAND;

        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ComponentName comp = null;
        if (!TextUtils.isEmpty(deviceBrand)) {
            if ("honor".equals(deviceBrand.toLowerCase()) || "huawei".equals(deviceBrand.toLowerCase())) {
                if (Build.VERSION.SDK_INT >= 26) {
                    comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity");
                } else if (Build.VERSION.SDK_INT >= 23) {
                    comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
                } else {
                    comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.com.huawei.permissionmanager.ui.MainActivity");
                }
            } else if ("xiaomi".equals(deviceBrand.toLowerCase())) {
                comp = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
            } else if ("vivo".equals(deviceBrand.toLowerCase())) {
                if (Build.VERSION.SDK_INT >= 26) {
                    comp = new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.PurviewTabActivity");
                } else {
                    comp = new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.SoftwareManagerActivity");

                }
            } else if ("oppo".equals(deviceBrand.toLowerCase())) {
                if (Build.VERSION.SDK_INT >= 26) {
                    comp = new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity");
                } else {
                    comp = new ComponentName("com.color.safecenter", "com.color.safecenter.permission.startup.StartupAppListActivity");
                }
            } else if ("samsung".equals(deviceBrand.toLowerCase())) {
                //三星samsung  samsung
//                comp = new ComponentName("com.samsung.android.sm_cn", "com.samsung.android.sm_cn.com.samsung.android.sm.ui.ram.AutoRunActivity");
                comp=ComponentName.unflattenFromString("com.samsung.android.sm_cn/com.samsung.android.sm.ui.ram.AutoRunActivity");
            }else if("meizu".equals(deviceBrand.toLowerCase())){
//                intent.setAction("com.meizu.safe.security.SHOW_APPSEC");
//                intent.addCategory(Intent.CATEGORY_DEFAULT);
//                intent.putExtra("packageName", HelpActivity.this.getPackageName());
            }
            else if("gionee".equals(deviceBrand.toLowerCase())){
                //金立
                comp = new ComponentName("com.gionee.softmanager", "com.gionee.softmanager.MainActivity");
            }else if("letv".equals(deviceBrand.toLowerCase())){
                //乐视
                comp =new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity");
            }else if("yulong".equals(deviceBrand.toLowerCase())){
                //酷派
                comp=new ComponentName("com.yulong.android.security", "com.yulong.android.seccenter.tabbarmain");
            }else if("smartisan".equals(deviceBrand.toLowerCase())){
                //锤子
//                intent.putExtra("packageName", HelpActivity.this.getPackageName());
                intent.addCategory(Intent.CATEGORY_DEFAULT);
//                comp=new ComponentName("com.smartisanos.security", "com.smartisanos.security.invokeHistory.InvokeHistoryActivity");
                intent.setAction("com.smartisanos.security.action.PACKAGE_DETAIL");
//                comp=new ComponentName("com.smartisanos.security", "com.smartisanos.security.PackageDetail");



            }
            //其他机型直接跳设置界面，适配的几个厂商中有不同系列的手机，可能会跳不到指定界面，因此需要在异常时调到普通设置界面做保护
            try {
//                if (comp == null) {
////                    intent = new Intent(Settings.ACTION_SETTINGS);
//                   try{
//                       startActivity(intent);
//                   }catch (Exception e){
//                       showToast("您的手机暂不需设置此功能，可跳过");
//                   }
//
//                } else {
                    intent.setComponent(comp);
                    startActivity(intent);
//                }
            } catch (Exception e) {//抛出异常就直接打开设置页面
                showToast("您的手机暂不需设置此功能，可跳过");
//                intent = new Intent(Settings.ACTION_SETTINGS);
//                startActivity(intent);
            }

        }
    }

    /**
     * 忽略电池优化
     */
    public void ignoreBattery(Context activity) {

        //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
        if (!isIgnoreBattery(activity)) {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            startActivity(intent);
        }
    }

    /**
     * 是否开启电池优化
     */

    public boolean isIgnoreBattery(Context activity) {

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        boolean isIgnoreBattery = false;
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                isIgnoreBattery = true;
            } else {
                isIgnoreBattery = powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
            }

        } catch (Exception e) {
            e.printStackTrace();
//            LogBackUtil.e(e.toString());
        }


        return isIgnoreBattery;
    }
}
